/**
 * 定时自动执行模块
 */

var MAX_MSEC = 300000;
var _cursec = MAX_MSEC;
var _fn_sec = null;
var _fn_complete = null;

/**
 * 初始化计时器
 * @param fn_complete 计时完成时的回调方法
 * @param fn_sec 每秒计时回调（用于显示倒计时，返回参数为当前剩余时间如："00:25:15"）
 * @param max 计时器上限（单位：秒）
 */
function init_timer( fn_complete, fn_sec, max )
{
	if( typeof ( fn_complete ) == "function" )
	{
		_fn_complete = fn_complete;
	}
	if( typeof ( fn_sec ) == "function" )
	{
		_fn_sec = fn_sec;
	}

	if( typeof ( max ) != "undefined" )
	{
		MAX_MSEC = parseInt( max * 1000 );
		_cursec = MAX_MSEC;
	}

	// 5分钟自动保存一次
	setInterval( "__timer_handler()", MAX_MSEC );
	setInterval( "__timer_second_handler()", 1000 );
}

function __timer_second_handler()
{
	_cursec -= 1000;
	var ts = ftime( "%h:%i:%s", _cursec );

	if( typeof ( _fn_sec ) == "function" )
	{
		_fn_sec( ts );
	}

	if( _cursec == 10000 )
		//infopad.msg( "10 秒后自动提交数据进行保存。" );

	if( _cursec == 0 )
		_cursec = MAX_MSEC;
}

function __timer_handler()
{
	if( typeof ( _fn_complete ) == "function" )
	{
		_fn_complete();
	}
}

/**
 * 将毫秒转换成 “天 时:分:秒 毫秒”
 * 
 * @param format 结果格式：%d-天，%h-时，%i-分，%s-秒，%l-毫秒
 * @param ms 毫秒数
 * @returns string
 */
function ftime( format, ms )
{
	var ss = 1000;
	var mi = ss * 60;//60000
	var hh = mi * 60;//3600000
	var dd = hh * 24;//86400000

	var day = parseInt( ms / dd );
	var hour = parseInt( ( ms - day * dd ) / hh );
	var minute = parseInt( ( ms - day * dd - hour * hh ) / mi );
	var second = parseInt( ( ms - day * dd - hour * hh - minute * mi ) / ss );
	var milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

	var strDay = day < 10 ? "0" + day : "" + day;
	var strHour = hour < 10 ? "0" + hour : "" + hour;
	var strMinute = minute < 10 ? "0" + minute : "" + minute;
	var strSecond = second < 10 ? "0" + second : "" + second;
	var strMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;
	strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : "" + strMilliSecond;

	var r = format;
	r = r.replace( /%d/ig, strDay );
	r = r.replace( /%h/ig, strHour );
	r = r.replace( /%i/ig, strMinute );
	r = r.replace( /%s/ig, strSecond );
	r = r.replace( /%l/ig, strMilliSecond );

	return r;
}
